package com.lingkang.top.seesister.network;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * okhttp 网络请求
 */
public class OkHttpRequest {
    //请求超时 /秒
    private static final int timeOut = 30;

    /**
     * Get 请求
     *
     * @return String
     */
    public static String get(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newBuilder().connectTimeout(timeOut, TimeUnit.SECONDS);
        try {
            try (Response response = client.newCall(request).execute()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Post 请求
     *
     * @return String
     */
    static String post(String url, Map<String, String> param) {
        FormBody.Builder body = new FormBody.Builder();
        for (String key : param.keySet()) {
            body.add(key, param.get(key)).build();
        }
        RequestBody requestBody = body.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newBuilder().connectTimeout(timeOut, TimeUnit.SECONDS);
        try {
            try (Response response = client.newCall(request).execute()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 盗链三方图片
     */
    static Bitmap getBitmapImg(String url) {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Referer","https://www.mzitu.com/")//简单过盗链
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newBuilder().connectTimeout(timeOut, TimeUnit.SECONDS);
        try {
            try (Response response = client.newCall(request).execute()) {
                return BitmapFactory.decodeStream(response.body().byteStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(OkHttpRequest.get("http://www.baidu.com"));
    }
}
